package proxy
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	
	public class PhotoProxy extends Proxy implements IEventDispatcher
	{
		private static const API_KEY:String = "3a662c08a083c6b5c0744e364b559bec";
		private static const FLICKR_URL:String = "http://api.flickr.com/services/rest/"
		private var eventDispatcher:EventDispatcher;
		private var pendingArgs:Array;
		public function PhotoProxy()
		{
			eventDispatcher = new EventDispatcher;
		}
		
		flash_proxy override function callProperty(name:*, ...parameters):*{
			this.pendingArgs = parameters;
			pendingArgs.unshift(API_KEY);
			
			var loader:URLLoader = new URLLoader;
			var url:String = FLICKR_URL + 
				"?method=flickr.reflection.getMethodInfo&method_name=flickr.photosets." + name.toString() + 
				"&api_key=" + API_KEY;
			url = encodeURI(url);
			var request:URLRequest = new URLRequest(url);
			
			loader.addEventListener(Event.COMPLETE,onReflectionComplete);
			loader.load(request);
			return name;
		}
		
		private function onReflectionComplete(event:Event):void{
			var queryString:String = "";
			var reflection:XML = XML(event.target.data);
			var methodArguments:XMLList = reflection.arguments.argument;
			for(var i:int=0;i,pendingArgs.length;i++){
				if(pending[i] != null){
					queryString += "&" + methodArguments.@name + "=" + pendingArgs[i];
				}
			}
			
			var loader:URLLoader = new URLLoader;
			var url:String = FLICKR_URL + 
				"?method=" + reflection.method.@name + queryString;
			url = encodeURI(url);
			var request:URLRequest = new URLRequest(url);
			
			loader.addEventListener(Event.COMPLETE,onComplete);
			loader.load(request);
			
		}
		
		private function onComplete(event:Event):void{
			this.dispatchEvent(new DataEvent(Event.COMPLETE,false,false,XML(event.target.data)));
		}
		
		public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
			eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
		}
		
		public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
		{
			eventDispatcher.removeEventListener(type, listener, useCapture);
		}
		
		public function dispatchEvent(event:Event):Boolean
		{
			return eventDispatcher.dispatchEvent(event);
		}
		
		public function hasEventListener(type:String):Boolean
		{
			return eventDispatcher.hasEventListener(type);
		}
		
		public function willTrigger(type:String):Boolean
		{
			return eventDispatcher.willTrigger(type);
		}
	}
}